﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using KingSite.Purview.Core.Service;
using KingSite.Purview.Services;
using KingSite.Purview.Domain;
using KingSite.Purview.Core.Repository;
using KingSite.Purview.Repository;
using KingSite.Purview.MVC;

namespace KingSite.Purview.WebUI.Controllers
{
    public class KSPRoleController : PurviewController
    {
        RoleProvider _roleProvider = Roles.Provider;
        MembershipProvider _membershipProvider = Membership.Provider;
        ISys_RoleInFunctionService _rifService = new Sys_RoleInFunctionService();
        ISys_RoleRepository _rp = new Sys_RoleRepository();

        public ActionResult Index(string roleName) {
            ViewBag.Message = "查看角色";
            string[] userList = Roles.GetUsersInRole(roleName);
            ViewData["RoleName"] = roleName;
            ViewData["UserList"] = userList;
            int total;
            MembershipUserCollection list = _membershipProvider.GetAllUsers(1, 1000, out total);
            IList<string> otherUserList = new List<string>();
            foreach (MembershipUser u in list) {
                if (!userList.Contains(u.UserName)) {
                    otherUserList.Add(u.UserName);
                }
            }

            MultiSelectList OtherUserList = new MultiSelectList(otherUserList);
            ViewData["OtherUserList"] = OtherUserList;
            MultiSelectList RoleUserList = new MultiSelectList(userList);
            ViewData["RoleUserList"] = RoleUserList;

            IList<Sys_RoleInFunctionModel> rifList = _rifService.FindByRoleName(_membershipProvider.ApplicationName, roleName);
            ViewData["Sys_RoleInFunctionModel"] = rifList;

            IList<Sys_FunctionModel> nList = _rifService.FindNotInRoleFunctionModel(_membershipProvider.ApplicationName, roleName);
            ViewData["nList"] = nList;
            return View();
        }

        public ActionResult List() {
            ViewBag.Message = "角色列表";
            string[] list = _roleProvider.GetAllRoles();
            ViewData["RoleList"] = list;
            return View();
        }

        public ActionResult Create() {
            return View();
        }

        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            string roleName = Request.Form["RoleName"];
            try
            {
                // TODO: Add insert logic here
                _roleProvider.CreateRole(roleName);                
                return RedirectToAction("List");
            }
            catch
            {
                return View();
            }
        }

        public ActionResult Delete(string roleName) {
            string[] roles = Roles.GetUsersInRole(roleName);
            if (roles.Count() > 0) {
                ModelState.AddModelError("error", "该角色下存在用户，不能删除！");
            }
            return RedirectToAction("Index", new { roleName = roleName });
        }

        public ActionResult AddUsersToRole(FormCollection form) {
            string opType = Request["OpType"];
            string roleName = Request["RoleName"];
            if (opType == "1") { //添加
                string otherUsers = Request["OtherUserList"];
                if (!string.IsNullOrEmpty(otherUsers)) {
                    string[] users = otherUsers.Split(',');
                    _roleProvider.AddUsersToRoles(users, new string[] { roleName });
                }

            }
            else {  //排除
                string roleUsers = Request["RoleUserList"];
                if (!string.IsNullOrEmpty(roleUsers)) {
                    string[] users = roleUsers.Split(',');
                    _roleProvider.RemoveUsersFromRoles(users, new string[] { roleName });
                }
            }
            return RedirectToAction("Index", new { roleName = roleName });
        }

        public ActionResult AddFunctionToRole(FormCollection form) {
            string roleName = Request["RoleName"];
            Sys_Role role = _rp.Find(_membershipProvider.ApplicationName,roleName);
            string opType = Request["Ck_OpType"];
            bool isChecked;
            IList<Sys_RoleInFunction> list = new List<Sys_RoleInFunction>();
            if (opType == "1") { //添加    
                foreach (string key in form.AllKeys) {
                    if (key.Contains("nck")) {
                        if (Boolean.TryParse(Request.Form.GetValues(key)[0], out isChecked)) {
                            if (isChecked) {
                                string[] ss = key.Split('_');
                                list.Add(new Sys_RoleInFunction { RoleId = role.Id, FunctionId = Convert.ToInt32(ss[1]) });
                            }
                        }

                    }
                }
                _rifService.AddRIF(list);
            }
            else {  //排除
                foreach (string key in form.AllKeys) {
                    if (key.Contains("dck")) {
                        if (Boolean.TryParse(Request.Form.GetValues(key)[0], out isChecked)) {
                            if (isChecked) {
                                string[] ss = key.Split('_');
                                list.Add(new Sys_RoleInFunction { RoleId = role.Id, FunctionId = Convert.ToInt32(ss[1]) });
                            }
                        }

                    }
                }
                _rifService.DeleteRIF(list);
            }
            return RedirectToAction("Index", new { roleName = roleName });
        }
    }
}
